package com.easyattendance.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.easyattendance.model.Class;
import com.easyattendance.model.Section;
import com.easyattendance.model.Subject;
import com.easyattendance.model.SubjectClass;
import com.easyattendance.model.SubjectTeacher;
import com.easyattendance.model.Teacher;
import com.easyattendance.nls.UseProperties;
import com.easyattendance.services.AddClassService;
import com.easyattendance.services.AddSectionService;
import com.easyattendance.services.AddSubjectService;
import com.easyattendance.services.AddTeacherService;
import com.easyattendance.services.LoginService;


@WebServlet(name = "AddSubjectServlet", urlPatterns = { "/AddSubjectServlet" })
public class AddSubjectServlet extends HttpServlet {
	
	private static final long serialVersionUID = -52821335972342214L;

	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {  
    	response.setContentType("text/html;charset=UTF-8");
		 PrintWriter out = response.getWriter();
		 boolean dispatcherFlag=false;
		 
		 AddSubjectService addSubjectService = new AddSubjectService();
	     AddSectionService addSectionService = new AddSectionService();
	     AddClassService addClassService = new AddClassService();
	     AddTeacherService addTeacherService = new AddTeacherService();
		 
	    String actionType = request.getParameter("action_type");
	    
	    if(actionType.equals("create")) {
	    	String subjectName = request.getParameter("subject_name");
	        String sectionEmail = addTeacherService.getSectionEmailIdByTeacherId((String)request.getSession().getAttribute("currentUser"));
	        String electiveType = request.getParameter("elective_select");
	        String classId = request.getParameter("class_id");
	        String[] teacherNames = request.getParameterValues("teacher_select");
	        
	        if(subjectName.isEmpty() || electiveType.isEmpty()){
	        	dispatcherFlag=true;
	        }
	        if(!dispatcherFlag){
		        boolean res = false;
		        SubjectTeacher[] sub_teacher = new SubjectTeacher[10];
		        
		        Subject newSubject = new Subject();
		        
		        Class classes = null;
		      
		        
		        // Add section foreign key to subject
		        boolean isSectionExists = addSectionService.ifAlreadyExists(sectionEmail);
		        
		        if (isSectionExists) {
		        	Section section = addSectionService.getSectionBySectionEmail(sectionEmail);
		            newSubject.setSection_id(section.getSection_id());
		  
		            res = true;
		        }
		        else {
		        	out.println("Section does not exist.. check your login");
		        	res = false;
		        }
		        
		        newSubject.setSubject_name(subjectName);
		        
		        if(electiveType == "" || electiveType.equals("Not Elective")) {
		        	 newSubject.setCategory("Not Elective");
		        }
		        else {
		        	newSubject.setCategory(electiveType);
		        }
	        
	        
		        boolean isSubjectExists = addSubjectService.ifAlreadyExists(newSubject);
		        String ID=null;
		        boolean result=false;
		        boolean result2=false;
		        boolean result3=false;
		        
		        if( ! isSubjectExists) {
		        	if (res) {
		        		Properties labels = UseProperties.loadProperties("Attendance.properties");
		            	//labels = UseProperties.incrementSubjectIdCounterValue(labels);
		            	ID = UseProperties.getSubjectIdPrefix(labels)+addSubjectService.getSubjectIdValue();
		            	
		            	//Add class foreign key
		                classes = addClassService.getClassByClassId_SectionEmail(classId, sectionEmail);
		            	newSubject.setClassObj(classes);
		            	
		            	//Add subject and subject teacher in subject_teacher table 
		            	for(int i=0; i <teacherNames.length; i++) {
		            		Teacher teacher = addTeacherService.getTeacherById(teacherNames[i]);
		            		// Mapping of subject and teacher
		            		sub_teacher[i]=new SubjectTeacher(teacher.getTeacher_id(),ID);
			                //
		            		//newSubject.getTeachers().add(teacher);
		            	}
		            	
		            	//Add subject
		            	newSubject.setSubject_id(ID);
		                result = addSubjectService.addSubject(newSubject);
		                
		                if(result) {
		                	for(int i=0; i<sub_teacher.length; i++) {
		                		if(sub_teacher[i]!= null) {
		                			result2=addSubjectService.addTeacherSubject(sub_teacher[i]);
		                			if(!result2) {
		                				break;
		                			}
		                		}
		                	}
		                	
			            	//Add subject and class in subject_class table
			            	SubjectClass subjectClass = new SubjectClass();
			            	subjectClass.setClass_id(classId);
			            	subjectClass.setSubject_id(ID);
			            	result3=addSubjectService.addSubjectClass(subjectClass);
			           }
		        	}
		        }
		        
				if (result && result2) {
					//out.println("<h1>Subject added Successfully</h1>");
					request.setAttribute("subjectAdded", "Subject added successfully.");
		        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addSubject.jsp");
		        	rd.forward(request, response);;
				} else {
					/*out.println("<h1>Subject not added successfully</h1>");
					out.println("To try again<a href=\"views/teacher/addSubject.jsp\">Click here</a>");*/
					
					Properties labels = UseProperties.loadProperties("Attendance.properties");
	            	labels = UseProperties.decrementSubjectIdCounterValue(labels);
					
					request.setAttribute("subjectNotAdded", "Subject Not Added successfully.");
		        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addSubject.jsp");
		        	rd.forward(request, response);
				}
	        }//if not dispatcher true
	        else{
	        	request.setAttribute("null_values", "All * fields are required.");
	        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addSubject.jsp");
	        	rd.forward(request, response);
	        }
	    }
	    else if(actionType.equals("update")) {
	    	int i = Integer.parseInt(request.getParameter("i_value"));
	    	boolean res = false;
	    	boolean result2=false;
	    	
	    	String subjectName = request.getParameter("subject_name"+i);
	    	String subjectId = request.getParameter("subject_id"+i);
	        String electiveType = request.getParameter("subject_category"+i);
	        String[] teacherNames = request.getParameterValues("teacher_select"+i);
	        
	        Subject subject = addSubjectService.getSubjectBySubjectId(subjectId);
	        subject.setCategory(electiveType);
	        subject.setSubject_name(subjectName);
	        
	        // Delete all existing sub teachers
	        if(teacherNames!=null) {
	        	addSubjectService.deleteSubTeachers(subjectId);
		        
	  	      //Add subject and subject teacher in subject_teacher table 
	          	for(int t=0; t <teacherNames.length; t++) {
	          		Teacher teacher = addTeacherService.getTeacherById(teacherNames[t]);
	          		// Mapping of subject and teacher
	          		SubjectTeacher sub_teacher=new SubjectTeacher(teacher.getTeacher_id(),subjectId);
	          			result2=addSubjectService.addTeacherSubject(sub_teacher);
	          			if( !result2) {
	      		        	break;
	      	        	}
	          	}
	        }
        	
	        res = addSubjectService.updateSubject(subject);
        	
	        if(res) {
        		//out.println("Subject UPdated Successfully");
	        	request.setAttribute("subjectUpdated", "Subject updated successfully.");
	        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/subjectSettings.jsp");
	        	rd.forward(request, response);
		    }
		    else {
		    	//out.println("Subject NOT Updated Successfully");
		    	request.setAttribute("subjectNotUpdated", "Subject not updated successfully.");
	        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/subjectSettings.jsp");
	        	rd.forward(request, response);
		   }
	    }
	    else if(actionType.equals("delete")) {
			int i = Integer.parseInt(request.getParameter("i_value"));
			String subjectId = request.getParameter("subject_id"+i);
			//Section section = addSectionService.getSectionBySectionEmail(sectionEmail);
			
			boolean res = addSubjectService.deleteSubject(subjectId);
			
			if(res){
				//out.println("Subject deleted successfully");
				request.setAttribute("subjectDeleted", "Subject deleted successfully.");
	        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/subjectSettings.jsp");
	        	rd.forward(request, response);
			}
			else {
				//out.println("Subject CANNOT be deleted successfully");
				request.setAttribute("subjectNotDeleted", "Subject Not deleted successfully.");
	        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/subjectSettings.jsp");
	        	rd.forward(request, response);
			}
		}
        else {
        	//out.println("Invalid action chosen.. Go back to select again");
        	request.setAttribute("invalidChoice", "Invalid Choice.. Go Back and choose again.");
        	RequestDispatcher rd = request.getRequestDispatcher("views/section/subjectSettings.jsp");
        	rd.forward(request, response);
        }
	  
    }

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>
}
